const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use((request,response,next)=>{
    response.set('Access-Control-Allow-Origin','*');
    // 允许任何请求头，必须写在中间件中，写在路由中，无效仍然会报跨域错误
    response.set('Access-Control-Allow-Headers','*');
    next();
})
app.use(bodyParser.urlencoded({extended:false}));
app.get('/ajax',(request, response)=>{
    
    console.log(request.headers.author);
    response.send('ajax 请求收到');
})
// 获取get请求的查询字符串参数 query参数
app.get('/query',(request, response)=>{
    console.log(request.query);
    response.send('query' + JSON.stringify(request.query));
})
 
// 获取params参数
app.get('/params/:name/:age',(request, response)=>{
    console.log(request.params);
    response.send('params' + JSON.stringify(request.params));
})
// IE
app.get('/ie',(request, response)=>{
    
    response.send('url = ' + request.url);
})

app.get('/json',(request, response)=>{
    let data = {
        username:'yuonly',
        age:18
    }
    // response.set('content-type','application/json;charset=utf-8');
    // response.end(JSON.stringify(data));
    response.json(data);
})

app.post('/post',(request, response)=>{
    response.send(JSON.stringify(request.body));
})

app.get('/timeout',(request, response)=>{
    setTimeout(()=>{
        response.send('timeout');
    },4000);
})

app.get('/jquery-get',(request, response)=>{
    console.log(request.query);
    response.json({ok:1,msg:'success'})
})

app.post('/jquery-post',(request, response)=>{
    console.log(request.body);
    response.json({ok:1,msg:'post - success'})
})
// jsonp

app.get('/jsonp',(request, response)=>{
    console.log('123123');
    response.send('ok');
})

app.listen(80,()=>{
    console.log('server run at 80');
})